package com.dongge.action;

import com.dongge.entity.Department;
import com.dongge.service.DepartmentService;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by Administrator on 2015/11/3.
 */
@Controller
@Scope("prototype")
public class DepartmentAction extends BaseAction<Department> implements CURDAction{

    @Resource
    private DepartmentService departmentService;

    private Long parentId;

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public String add() {//parent department？
        if(parentId != null){
            Department parent = departmentService.get(parentId);
            model.setParent(parent);
        }
        departmentService.save(model);
        if(model.getParent()!=null){
            parentId = model.getParent().getId();
        }
        else{
            parentId = null;
        }
        return "toList";
    }

    public String addPrepare() {
        List<Department> departments = departmentService.getAll();
        ActionContext.getContext().put("departments",departments);
        return "addPrepare";
    }

    public String delete() {
        departmentService.delete(model.getId());
        return "toList";
    }

    public String edit() {
        if(parentId != null){
            Department parent = departmentService.get(parentId);
            model.setParent(parent);
        }
        departmentService.update(model);
        if(model.getParent()!=null){
            parentId = model.getParent().getId();
        }
        else {
            parentId = null;
        }
        return "toList";
    }

    /**
     * 准备参数包括所有部门，以及当前部门信息
     * @return
     */
    public String editPrepare() {
        List<Department> departments = departmentService.getAll();
        ActionContext.getContext().put("departments", departments);
        Department department = departmentService.get(model.getId());
        ActionContext.getContext().getValueStack().push(department);
        return "editPrepare";
    }

    public String list() {//应该只要显示当前级别的部门
        List<Department> departments = departmentService.findDepartmentsByParentId(parentId);
        ActionContext.getContext().put("departments", departments);
        return "list";
    }
}
